package com.appcloner.ui.card

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.appcloner.data.repository.CardRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class CardVerificationUiState(
    val cardKey: String = "",
    val isLoading: Boolean = false,
    val error: String? = null,
    val isVerified: Boolean = false
)

@HiltViewModel
class CardVerificationViewModel @Inject constructor(
    private val cardRepository: CardRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(CardVerificationUiState())
    val uiState: StateFlow<CardVerificationUiState> = _uiState.asStateFlow()
    
    fun onCardKeyChange(newKey: String) {
        _uiState.update { it.copy(cardKey = newKey, error = null) }
    }
    
    fun verifyCard(onSuccess: () -> Unit) {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            
            try {
                val result = cardRepository.verifyCard(uiState.value.cardKey)
                if (result.isSuccess) {
                    _uiState.update { it.copy(isVerified = true, isLoading = false) }
                    onSuccess()
                } else {
                    _uiState.update { 
                        it.copy(
                            error = result.exceptionOrNull()?.message ?: "验证失败",
                            isLoading = false
                        ) 
                    }
                }
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(
                        error = e.message ?: "网络错误",
                        isLoading = false
                    ) 
                }
            }
        }
    }
}
